package work.atpgroup.interceptor;

import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.HandlerInterceptor;
import work.atpgroup.entity.User;
import work.atpgroup.service.ResourceService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

@Controller("resourceInterceptor")
public class ResourceInterceptor implements HandlerInterceptor {
    @Resource(name="resourceService")
    private ResourceService resourceService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String servletPath = request.getServletPath();
        char[] bytes = servletPath.toCharArray();
        String resource_identification = "";
        for(int i = bytes.length-1;i>=0;i--){
            if(bytes[i]>='0'&&bytes[i]<='9'){
                resource_identification = bytes[i]+resource_identification;
            }else{
                break;
            }
        }

        int resource_id = -1;
        try{
            resource_id = Integer.parseInt(resource_identification);
        }catch(Exception e){
            e.printStackTrace();
        }
        User user = (User) request.getSession().getAttribute("user");
        return Objects.equals(user.getUserId(), resourceService.getUserIdByResourceId(resource_id));
    }

}
